<template>
  <el-dialog
    :title="`${formModel.id ? '修改学科' : '新增学科'}`"
    :visible="showDialog"
    width="400px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :rules="formRules"
      :model="formModel"
      label-width="80px"
    >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="formModel.subjectName"
          placeholder="请输入学科名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
          v-model="formModel.isFrontDisplay"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>
    <div slot="footer" style="text-align: right">
      <el-button @click="$emit('update:showDialog', false)">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入添加学科,删除学科,获取学科详情的方法
import { add as addSubjectApi, update as editSubjectApi, detail as getSubjectDetailApi } from '@/api/hmmm/subjects.js'
export default {
  props: {
    // 控制对话框显示与隐藏
    showDialog: {
      type: Boolean,
      default: false
    }
    // 当前操作的学科
    // currentSubject: {
    //   type: Object,
    //   default: () => ({})
    // }
  },
  data () {
    return {
      // 表单校验规则
      formRules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      },
      // 表单数据对象
      formModel: {
        subjectName: '',
        isFrontDisplay: 0
      }
    }
  },
  methods: {
    // 监听对话框的关闭
    handleClose () {
      this.$emit('update:showDialog', false)
      this.$refs.formRef.resetFields()
      this.formModel = {
        subjectName: '',
        isFrontDisplay: 0
      }
    },
    // 点击确定按钮触发的事件
    async submitForm () {
      try {
        await this.$refs.formRef.validate()
        if (this.formModel.id) {
          // 修改
          await editSubjectApi(this.formModel)
          this.$message.success('修改成功')
        } else {
          // 新增
          await addSubjectApi(this.formModel)
          this.$message.success('添加成功')
        }
        this.$emit('update:showDialog', false)
        this.$parent.getSubjectsList()
      } catch (error) {
        console.log(error)
        this.$message.error('表单有误')
      }
    },
    async getSubjectDetail (id) {
      const { data } = await getSubjectDetailApi({ id })
      // console.log(data)
      this.formModel = data
    }
  }
}
</script>

<style scoped lang='less'></style>
